import axios from "axios";
import store from '@/store'
import { ElMessage } from 'element-plus'
import router from '@/router'


axios.defaults.timeout = 50000;

axios.interceptors.request.use(

    config => {
        const isToken = (config.headers || {}).isToken === false
        const  token = store.state.token;
        if (token && !isToken) {
            config.headers.Authorization = `Bearer ${token}`
        }
        return config
    }, e => Promise.reject(e))

axios.interceptors.response.use(
    (response) => {
        if(response.data.code  && response.data.code != 0){
            ElMessage(
                {
                    message: response.data.msg,
                    type: 'warning',
                }
            )
        }
        return response
    },
    async (error) => {
        let uurl = window.location.href;

        if( error.config.url === '/oauth/token'  &&  error.response.status  === 400 ){
            if(error.config.params.refresh_token){
                router.push({path:"login",query:{urlll: uurl.split("#")[1]}})
                return Promise.reject(error)
            }
            ElMessage.error(error.response.data.error_description)
            return Promise.reject(error)
        }else if(error.response.status  == 401){


            if(error.config.url !== '/oauth/token' && store.state.refreshToken){
                await store.dispatch("refresh_token").then(()=>{
                    window.location.reload();
                    return Promise.reject(error)
                })
            }else {
                let re_url = uurl.split("#")[1]
                if( re_url == "/login"){
                    re_url = "/"
                }
                router.push({path:"login",query:{urlll: re_url}})
                return Promise.reject(error)
            }
        }else {
            ElMessage.error('服务器出问题啦，请联系管理员')
            return Promise.reject(error)
        }
    }
)

export default axios;
